package main

import (
	"encoding/json"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common"
	"github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/common/profile"
	v20210323 "github.com/tencentcloud/tencentcloud-sdk-go/tencentcloud/dnspod/v20210323"
	"github.com/wonderivan/logger"
	"io"
	"net/http"
	"os"
	"strconv"
	"strings"
	"time"
)

var (
	dom  = "top"
	ak   = ""
	sk   = ""
	ip   = ""
	id   uint64
	line = "默认"
)

func getIp() string {
	responseClient, err := http.Get("https://ip.3322.net") // 获取外网 IP
	if err != nil {
		logger.Info("获取外网 IP 失败，请检查网络\n")
		return ""
	}
	defer responseClient.Body.Close()
	body, _ := io.ReadAll(responseClient.Body)
	ip := string(body)
	return strings.ReplaceAll(ip, "\n", "")
}

func update() {
	temp := getIp()
	logger.Info("ip为：%s", temp)
	if temp == ip {
		return
	}
	ip = temp
	client, err := v20210323.NewClient(common.NewCredential(ak, sk), "", profile.NewClientProfile())
	//print(err)
	//reReq := v20210323.NewDescribeRecordListRequest()
	//reReq.Domain = &dom
	//re,err := client.DescribeRecordList(reReq)
	//print(re)
	//print(err)
	req := v20210323.NewModifyDynamicDNSRequest()
	req.Domain = &dom
	req.Value = &ip
	req.RecordId = &id
	req.RecordLine = &line
	res, err := client.ModifyDynamicDNS(req)
	if err != nil {
		logger.Error(err)
	}
	resStr, _ := json.Marshal(res)
	logger.Info(string(resStr))
}

func init() {
	ak = os.Getenv("AK")
	sk = os.Getenv("SK")
	dom = os.Getenv("DOMAIN")
	idInt, _ := strconv.Atoi(os.Getenv("ID"))
	id = uint64(idInt)
}

func main() {
	update()
	t := time.NewTicker(time.Minute * 10)
	for {
		select {
		case <-t.C:
			update()
		}
	}
}
